const db = require('../config/db');

class User {
  static async create(name, email) {
    try {
      const [result] = await db.execute(
        'INSERT INTO users (name, email) VALUES (?, ?)',
        [name, email]
      );
      return result.insertId;
    } catch (error) {
      console.error('Error creating user:', error);
      throw error;
    }
  }

  static async findById(id) {
    try {
      const [rows] = await db.execute(
        'SELECT * FROM users WHERE id = ?',
        [id]
      );
      return rows[0];
    } catch (error) {
      console.error('Error finding user:', error);
      throw error;
    }
  }

  static async findUser(email) {
    try {
      const [rows] = await db.execute(
        'SELECT * FROM users WHERE email = ?',
        [email]
      );
      return rows[0];
    } catch (error) {
      console.error('Error finding user:', error);
      throw error;
    }
  }

  static async saveFaceDescriptor(userId, descriptor, imagePath) {
    try {
      // 确保描述符是有效的 JSON 字符串
      const descriptorJson = Array.isArray(descriptor) ? 
        JSON.stringify(descriptor) : 
        (typeof descriptor === 'string' ? descriptor : JSON.stringify([]));
      
      const [result] = await db.execute(
        'INSERT INTO face_descriptors (user_id, descriptor, image_path) VALUES (?, ?, ?)',
        [userId, descriptorJson, imagePath]
      );
      return result.insertId;
    } catch (error) {
      console.error('保存人脸描述符时出错:', error);
      throw error;
    }
  }

  static async getFaceDescriptors() {
    try {
      const [rows] = await db.execute(
        'SELECT u.id, u.name, fd.descriptor FROM users u JOIN face_descriptors fd ON u.id = fd.user_id'
      );
      
      // 添加数据验证和错误处理
      const validDescriptors = [];
      
      for (const row of rows) {
        try {
          // 确保描述符是有效的数组
          if (Array.isArray(row.descriptor)) {
            validDescriptors.push({
              userId: row.id,
              name: row.name,
              descriptor: row.descriptor
            });
          } else {
            console.warn(`用户 ${row.id} 的描述符不是有效数组，已跳过`);
          }
        } catch (error) {
          console.warn(`解析用户 ${row.id} 的描述符时出错: ${error.message}，已跳过`);
        }
      }
      
      return validDescriptors;
    } catch (error) {
      console.error('获取人脸描述符时出错:', error);
      throw error;
    }
  }
}
module.exports = User;